package ffm.database.wrappers;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class TomcatDSWrapper 
{
	protected DataSource m_dsTomcatDS;
	
	public String m_sDatabaseName;
	public String m_sServer;
	public String m_sUserName;
	public String m_sPassword;
	
	public boolean m_bUseDirect = false;
	
	public TomcatDSWrapper() 
	{
	}
	
	public void Initialise(String sDSName) throws NamingException
	{
		Context initContext = new InitialContext();
		Context envContext  = (Context)initContext.lookup("java:/comp/env");
		m_dsTomcatDS = (DataSource)envContext.lookup(sDSName);
	}
	
	public void InitialiseWithContext(String sDSName, Context cCxt) throws NamingException
	{
		m_dsTomcatDS = (DataSource)cCxt.lookup(sDSName);
	}
	
	public Connection GetDirectConnection(String dbName, String sServer, String sUserName, String sPassword) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException
	{
		String url = "jdbc:mysql://"+sServer+":3306/";
        String driver = "com.mysql.jdbc.Driver";
        String userName = sUserName;
        String password = sPassword;
        Class.forName(driver).newInstance();
        
        Connection conn = DriverManager.getConnection(url+dbName,userName,password);
        return conn; 
	}
	
	public Connection GetLocalConnection(String dbName) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException
	{
		String url = "jdbc:mysql://localhost:3306/";
        String driver = "com.mysql.jdbc.Driver";
        String userName = "root";
        String password = "qazxsw";
        Class.forName(driver).newInstance();
        
        Connection conn = DriverManager.getConnection(url+dbName,userName,password);
        return conn; 
	}
	
	public Connection GetConnection() throws SQLException
	{
		if ( m_bUseDirect )
		{
			Connection conn;
			try
			{
				 conn = GetDirectConnection(m_sDatabaseName,m_sServer,m_sUserName,m_sPassword);
			}
			catch(Exception e)
			{
				throw new SQLException("Can't connect to the database",e);
			}
			
			return conn;
		}
			
		return m_dsTomcatDS.getConnection();
	}
	
}
